package com.zss.leetcode;


/**
 * 2.两数相加
 * @author fuguozhang
 * @create 2022/5/14
 */
public class TwoAdd {

    public static void main(String[] args) {
        ListNode node1 = new ListNode(2);
        ListNode node2 = new ListNode(4);
        ListNode node3 = new ListNode(3);
        node1.setNext(node2);
        node2.setNext(node3);

        ListNode nodeA = new ListNode(5);
        ListNode nodeB = new ListNode(6);
        ListNode nodeC = new ListNode(4);
        nodeA.setNext(nodeB);
        nodeB.setNext(nodeC);

        ListNode result = twoAdd(node1,nodeA);
        while (result != null){
            System.out.println(result.value);
            result = result.next;
        }

    }

    public static ListNode twoAdd(ListNode node1,ListNode node2){
            ListNode head = null;
            ListNode tail = null;
            int carry = 0;
            while(node1 != null || node2 != null){
                int val1 = node1 != null ? node1.value : 0;
                int val2 = node2 != null ? node2.value : 0;
                int sum = val1 + val2 + carry;
                if(head == null){
                    head = new ListNode(sum % 10);
                    tail = head;
                }else {
                    tail.next = new ListNode(sum % 10);
                    tail = tail.next;
                }
                carry = sum / 10;
                if(node1 != null){
                    node1 = node1.next;
                }
                if(node2 != null){
                    node2 = node2.next;
                }
            }
            if(carry > 0){
                tail.next = new ListNode(carry);
            }
            return head;
    }

    public static class ListNode{
        private int value;
        private ListNode next;

        public ListNode(int value){
            this.value = value;
        }

        public void setNext(ListNode next) {
            this.next = next;
        }
    }
}
